using System;
using System.Text;
using System.Security.Cryptography;

namespace DecisionesInteligentes.iEvalua.Helpers
{
	public class Password {
		public string ComputeSaltedHash(string password, byte[] salt)
		{
			
			// Create Byte array of password string
			ASCIIEncoding encoder = new ASCIIEncoding();
			Byte[] secretBytes = encoder.GetBytes(password);

			// append the two arrays
			Byte[] toHash = new Byte[secretBytes.Length + salt.Length];
			Array.Copy(secretBytes, 0, toHash, 0, secretBytes.Length);
			Array.Copy(salt, 0, toHash, secretBytes.Length, salt.Length);

			SHA1 sha1 = SHA1.Create();
			Byte[] computedHash = sha1.ComputeHash(toHash);

			return Convert.ToBase64String(salt) + Convert.ToBase64String(computedHash);
		}
		
		public bool VerifyPassword(string password, string saltedhashedPassword)
		{
			if (saltedhashedPassword.Length < 8) {
				return false;
			}
			
			string salt = saltedhashedPassword.Substring(0, 8);
			byte[] saltBytes = Convert.FromBase64String(salt);
			
			return saltedhashedPassword == ComputeSaltedHash(password, saltBytes);
		}
		
		public byte[] CreateRandomSalt()
		{
			byte[] saltBytes = new Byte[4];
			RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
			rng.GetBytes(saltBytes);

			return saltBytes;
			
		}
	}
}